trigger AddShareToOwner on CityNameList__c (after insert,after delete) {
    List<HCPEducation__Share> nhcpsList = new List<HCPEducation__Share>();
    List<ID> idList1 = new List<ID>();
    List<ID> idList2 = new List<ID>();
    List<HCPEducation__Share> ahcpsList = new List<HCPEducation__Share>();
    List<HCPEducation__Share> dhcpsList = new List<HCPEducation__Share>();
    
    if(system.trigger.isinsert){
        for(CityNameList__c  cnl: Trigger.new)
        {   
            HCPEducation__Share nhcpShare = new HCPEducation__Share();
            nhcpShare.ParentId = (ID)cnl.NationalHCPID__c;
            nhcpShare.UserOrGroupId = cnl.ownerid;
            nhcpShare.AccessLevel = 'Read';
            nhcpsList.add(nhcpShare);
        }
        insert nhcpsList;
    }
    if(system.trigger.isdelete){
        for(CityNameList__c  cnl: Trigger.old)
        {
            idList1.add(cnl.ownerid);
            idList2.add(cnl.NationalHCPID__c);
        }
        ahcpsList = [Select id,UserOrGroupId,ParentId  From HCPEducation__Share Where UserOrGroupId in: idList1 and ParentId in: idList2];
        for(CityNameList__c  cnl1: Trigger.old)
        {
            for(HCPEducation__Share hcps:ahcpsList)
            {
                if((cnl1.ownerid == hcps.UserOrGroupId)&&(cnl1.NationalHCPID__c== hcps.ParentId ))
                {
                    dhcpsList.add(hcps);
                    break;
                }
            }
        }
        delete dhcpsList;
    } 
}